package com.nsi.service.Impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nsi.common.Const;
import com.nsi.common.ServerResponse;
import com.nsi.dao.ConfigureMapper;
import com.nsi.dao.LogMapper;
import com.nsi.dao.SchoolNewMapper;
import com.nsi.exception.NsiOperationException;
import com.nsi.pojo.Configure;
import com.nsi.pojo.Log;
import com.nsi.pojo.SchoolNew;
import com.nsi.service.INewSchoolService;
import com.nsi.service.TemplateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Luo Zhen
 * @create 2019-05-13 17:42
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class NewSchoolServiceImpl extends ServiceImpl<SchoolNewMapper, SchoolNew> implements INewSchoolService {

    @Autowired
    private SchoolNewMapper schoolNewMapper;
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private TemplateService templateService;
    @Autowired
    private ConfigureMapper configureMapper;

    @Override
    public SchoolNew insertSchool(SchoolNew schoolNew) {
        if (StringUtils.isEmpty(schoolNew.getSchoolName())) {
            throw new NsiOperationException("参数不合法");
        }
        int count = schoolNewMapper.insert(schoolNew);
        if (count <= 0) {
            throw new NsiOperationException("添加失败");
        }
        //todo 上传模板
        //todo 上传OOS
        return schoolNew;
    }

    @Override
    public PageInfo findAll(Integer pageNum, Integer pageSize, String searchKey, Integer verifySign) {
        PageHelper.startPage(pageNum, pageSize);
        List<SchoolNew> schoolNewList = this.findAllList(searchKey, verifySign);
        PageInfo pageInfo = new PageInfo(schoolNewList);
        return pageInfo;
    }

    @Override
    public List<SchoolNew> findAllList(String searchKey, Integer verifySign) {
        List<SchoolNew> schoolNewList = schoolNewMapper.findAll(searchKey, verifySign);
        return schoolNewList;
    }

    @Override
    public ServerResponse findAll() {
        List<SchoolNew> newSchoolItem = schoolNewMapper.findNewSchoolItem();
        return ServerResponse.createBySuccess(newSchoolItem);
    }

    @Override
    public SchoolNew findById(Integer schoolId) {
        SchoolNew school = schoolNewMapper.selectById(schoolId);
        return school;
    }

    @Override
    public ServerResponse modifyNewSchool(SchoolNew schoolNew) {
        Configure templateString = configureMapper.findByType(Const.SCHOOL_TYPE);
        if (templateString == null) {
            throw new NsiOperationException("学校模板为空!");
        }
        if (StringUtils.isBlank(schoolNew.getSchoolName()) || schoolNew.getId() == null) {
            throw new NsiOperationException("参数不合法");
        }
        try {
            schoolNew.setCreateTime(new Date());
            schoolNewMapper.updateById(schoolNew);
            // 上传OOS
            templateService.uploadSchoolTemplateOOS(schoolNew, templateString);
        } catch (Exception e) {
            log.error("【后台修改学校库信息异常】msg:{}", e.getMessage());
            throw new NsiOperationException("update newSchool error:" + e.getMessage());
        }
        return ServerResponse.createBySuccess("修改成功");
    }

    /**
     * 学校模板合成
     *
     * @param school
     * @param configure
     * @return
     */
    private String templateCompound(SchoolNew school, Configure configure) {
        return configure.getTextcontent01()
                .replaceAll("SCHOOL---NAME", school.getSchoolName())
                .replaceAll("SCHOOL---ENGLISH---NAME", school.getSchoolEnglishName())
                .replaceAll("SCHOOL---PROPERTIES", school.getSchoolProperties())
                .replaceAll("SCHOOL---FOUNDTIME", (school.getFoundingTime() == null) ? "暂无" : "" + school.getFoundingTime())
                .replaceAll("SCHOOL---NUMALL", (school.getStudents() == null) ? "暂无" : "" + school.getFoundingTime())
                .replaceAll("SCHOOL---FILINGFEE", this.replaceValue(school.getFilingFee()))
                .replaceAll("SCHOOL---WEBSITE", this.replaceValue(school.getWebsite()))
                .replaceAll("SCHOOL---TELPHONE", this.replaceValue(school.getTelephone()))
                .replaceAll("SCHOOL---DESC", this.replaceValue(school.getSchoolDesc()))
                .replaceAll("SCHOOL---HARDWARE", this.replaceValue(school.getHardware()))
                .replaceAll("SCHOOL---MANAGEMENT", this.replaceValue(school.getSchoolManagement()))
                .replaceAll("SCHOOL---COURSESYSTEM", this.replaceValue(school.getCourseSystem()));
    }

    private String replaceValue(String str) {
        if ("0".equals(str) || StringUtils.isEmpty(str)) {
            return "暂无";
        } else {
            return str;
        }
    }

    @Override
    public ServerResponse deleteById(Integer schoolId) {
        if (schoolId == null) {
            throw new NsiOperationException("参数不合法");
        }
        try {
            SchoolNew schoolNew = new SchoolNew();
            schoolNew.setId(schoolId);
            schoolNew.setStatus(Const.HIDE_STATUS);

            schoolNewMapper.updateById(schoolNew);
        } catch (Exception e) {
            throw new NsiOperationException("delete newSchool error:" + e.getMessage());
        }
        return ServerResponse.createBySuccessMessage("删除成功");
    }

    @Override
    public ServerResponse<PageInfo> searchPowerList(String[] area, String[] system, String[] properties, String[] course, int pageNum, int pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<String> listAreas = null;
        List<String> listSystem = null;
        List<String> listProperties = null;
        List<String> listCourse = null;
        if (area != null) {
            listAreas = Arrays.asList(area);
        }
        if (system != null) {
            listSystem = Arrays.asList(system);
        }
        if (properties != null) {
            listProperties = Arrays.asList(properties);
        }
        if (course != null) {
            listCourse = Arrays.asList(course);
        }
        List<SchoolNew> schoolList = schoolNewMapper.searchPowerList(listAreas, listSystem, listProperties, listCourse);
        PageInfo pageInfo = new PageInfo(schoolList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse findCityWideList(Integer id) {
        // 根据市查询
        List<SchoolNew> cityWideList = schoolNewMapper.findCityWideBytown(id);
        if (cityWideList != null && cityWideList.size() >= Const.CITY_WIDE_SIZE) {
            return ServerResponse.createBySuccess(cityWideList);
        }

        // 根据省查询
        cityWideList = schoolNewMapper.findCityWideByprovince(id);
        if (cityWideList != null && cityWideList.size() >= Const.CITY_WIDE_SIZE) {
            return ServerResponse.createBySuccess(cityWideList);
        }
        cityWideList = schoolNewMapper.findCityWideByrand();
        return ServerResponse.createBySuccess(cityWideList);
    }

    //检查学校名 是否有重复
    @Override
    public ServerResponse checkValidedByName(String schoolName) {
        if (StringUtils.isBlank(schoolName)) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        int rowCount = schoolNewMapper.checkBySchoolName(schoolName);
        if (rowCount > 0) {
            return ServerResponse.createByErrorMessage("学校名字已存在");
        }
        return ServerResponse.createBySuccessMessage("验证成功");

    }

    @Override
    public ServerResponse updateTemplate() {
        Configure templateString = configureMapper.findByType(Const.SCHOOL_TYPE);
        if (templateString == null) {
            throw new NsiOperationException("学校模板为空!");
        }
        List<SchoolNew> schoolLists = schoolNewMapper.selectList(null);
        try {
            schoolLists.stream()
                    .peek(school -> {
                        templateService.uploadSchoolTemplateOOS(school, templateString);
                    });
        } catch (Exception e) {
            log.error("【上传学校页面异常】msg:{}", e.getMessage());
        }
        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse school_UpdataButton(String schoolId, String schoolName, String userMail) {
        Log log = new Log();
        log.setSign("学校请求更新");
        log.setIndex01(schoolName);
        log.setIndex02(new Date());
        log.setIndex03(schoolId);
        log.setIndex04(userMail);
        int i = logMapper.insert(log);
        if (i == 1) {
            return ServerResponse.createBySuccess("success");
        } else {
            return ServerResponse.createByErrorMessage("插入失败");
        }
    }

    @Override
    public ServerResponse list_schoolUpdataButton() {
        List<Log> list = logMapper.selectList(
                new EntityWrapper<Log>()
                        .eq("sign", "学校请求更新"));
        return ServerResponse.createBySuccess(list);
    }

    @Override
    public ServerResponse delete_schoolUpdataButton(int id) {
        int i = logMapper.deleteById(id);
        if (i == 1) {
            return ServerResponse.createBySuccessMessage("删除成功");
        } else {
            return ServerResponse.createByErrorMessage("删除失败");
        }
    }

    @Override
    public ServerResponse verifyStatus(Integer schoolId, Integer status) {
        SchoolNew schoolNew = new SchoolNew();
        schoolNew.setId(schoolId);
        schoolNew.setVerifySign(status);
        schoolNewMapper.updateById(schoolNew);
        return ServerResponse.createBySuccessMessage("修改成功");
    }


}
